/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    int maxPath(TreeNode* root, int& ans) {
        if (root == nullptr)
            return 0;
        int sum = root->val;
        int leftmax = max(maxPath(root->left, ans), 0);
        int rightmax = max(maxPath(root->right, ans), 0);
        sum += (leftmax + rightmax);
        ans = max(sum, ans);
        return root->val + max(leftmax, rightmax);
    }
    int maxPathSum(TreeNode* root) {
        int ans = -1000;
        maxPath(root, ans);
        return ans;
    }
};